package com.gitee.zhanyao.monomer.service.impl;

import com.gitee.zhanyao.monomer.entity.QSysUserRole;
import com.gitee.zhanyao.monomer.entity.SysUserRole;
import com.gitee.zhanyao.monomer.repository.SysUserRoleRepository;
import com.gitee.zhanyao.monomer.service.SysUserRoleService;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.collections4.IterableUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhanyao
 */
@Transactional
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    @Override
    public List<SysUserRole> getUserRoles(String userId) {
        QSysUserRole qSysUserRole = QSysUserRole.sysUserRole;
        Predicate predicate = qSysUserRole.sysUser.id.eq(userId);
        return IterableUtils.toList(sysUserRoleRepository.findAll(predicate));
    }

    @Override
    public Set<String> getDistinctUserRoles(String userId) {
        QSysUserRole qSysUserRole = QSysUserRole.sysUserRole;
        List<String> stringList = jpaQueryFactory.selectDistinct(qSysUserRole.sysRole.code)
                .from(qSysUserRole).where(qSysUserRole.sysUser.id.eq(userId)).fetch();
        return new HashSet(stringList);
    }
}
